import axios from '../utils/axios.js'
import qs from 'qs'
import pool from '../DB/db.js'
// 推送钉钉机器人通知
export const sendDingTalkMessage = (data, ding_talk_token) => {
  //   console.log('推送钉钉机器人通知 >>>', ding_talk_token)
  const url = `https://oapi.dingtalk.com/robot/send?access_token=${ding_talk_token}`
  try {
    return axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json;charset=UTF-8',
        accept: 'application/json;charset=UTF-8',
      },
    })
  } catch (error) {
    console.error('Error occurred:')
  }
}
// 推送TG机器人通知
export const sendTelegramMessage = (params) => {
  const { text, tg_chat_id, tg_bot_token } = params
  const data = {
    chat_id: tg_chat_id,
    text,
  }
  //   console.log('推送TG机器人通知 >>>', tg_chat_id, tg_bot_token)
  try {
    return axios.post(`https://api.telegram.org/bot${tg_bot_token}/sendMessage`, data, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    })
  } catch (error) {
    console.error('Error occurred:')
  }
}
export function sendDingTalkMsgFn({ task_name, added, login_name, isExpired }) {
  // 查询数据
  const selectSql = `SELECT * FROM users WHERE login_name = ?;`
  pool.all(selectSql, [login_name], (err, rows) => {
    if (rows && rows[0]) {
      //   console.log('rows[0] >>>', rows[0])
      let ding_talk_token = rows[0].ding_talk_token
      let tg_bot_token = rows[0].tg_bot_token
      let tg_chat_id = rows[0].tg_chat_id
      if (!ding_talk_token && !tg_bot_token) return //没有token不发消息通知
      if (isExpired) {
        let text = `###### 云盘更新通知 \n #### [登录cookies已失效，请重新登录！](h)  \n`
        let msgCard = {
          msgtype: 'markdown',
          markdown: {
            title: '云盘通知',
            text,
          },
        }
        tg_chat_id && tg_bot_token && sendTelegramMessage({ text, tg_chat_id, tg_bot_token })
        ding_talk_token && sendDingTalkMessage(msgCard, ding_talk_token)
      }
      let text = `###### 云盘更新通知 \n #### [${task_name} 更新${added.length}集](h)  \n`
      added.slice(0, 10).forEach((file) => {
        text += `- ${file.name} \n`
      })
      if (added.length > 10) {
        text += `- ...\n - ${added.length - 10} 个文件未显示 \n `
      }
      let msgCard = {
        msgtype: 'markdown',
        markdown: {
          title: '云盘通知',
          text,
        },
      }
      tg_chat_id && tg_bot_token && sendTelegramMessage({ text, tg_chat_id, tg_bot_token })
      ding_talk_token && sendDingTalkMessage(msgCard, ding_talk_token)
    }
  })
}
